import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { UsersMePresenceNet } from '@/api/UsersMePresenceNet'

// 状态转换工具函数
export const convertStatusToString = (status: number | string): 'online' | 'offline' => {
  if (typeof status === 'string') {
    return status === 'online' ? 'online' : 'offline'
  }
  return status === 1 ? 'online' : 'offline'
}

export const convertStatusToNumber = (status: 'online' | 'offline'): number => {
  return status === 'online' ? 1 : 0
}

// 用户信息接口
export interface UserInfo {
  id: string
  email: string
  nickname: string
  avatar: string
  signature: string
  status: number // 0: 离线, 1: 在线
  lastSeen?: Date
}

// 用户状态管理
export const useUserStore = defineStore('user', () => {
  const currentUser = ref<UserInfo | null>(null)
  const isLoggedIn = computed(() => !!currentUser.value)

  // 登录
  const login = (userInfo: Omit<UserInfo, 'id' | 'lastSeen'>) => {
    currentUser.value = {
      id: Date.now().toString(),
      ...userInfo,
      status: 1, // 登录后默认在线
    }
    localStorage.setItem('user', JSON.stringify(currentUser.value))
  }

  // 登出
  const logout = () => {
    currentUser.value = null
    localStorage.removeItem('user')
  }

  // 更新用户信息
  const updateUserInfo = (updates: Partial<UserInfo>) => {
    if (currentUser.value) {
      currentUser.value = { ...currentUser.value, ...updates }
      localStorage.setItem('user', JSON.stringify(currentUser.value))
    }
  }

  // 更新在线状态
  const updateStatus = async (status: UserInfo['status']) => {
    if (currentUser.value) {
      try {
        // 调用API同步状态到服务器
        await UsersMePresenceNet({ status })

        // 更新本地状态
        currentUser.value.status = status
        if (status === 0) {
          currentUser.value.lastSeen = new Date()
        }
        localStorage.setItem('user', JSON.stringify(currentUser.value))
      } catch (error) {
        console.error('更新在线状态失败:', error)
        // 即使API调用失败，也更新本地状态
        currentUser.value.status = status
        if (status === 0) {
          currentUser.value.lastSeen = new Date()
        }
        localStorage.setItem('user', JSON.stringify(currentUser.value))
      }
    }
  }

  // 初始化用户信息（从localStorage恢复）
  const initUser = () => {
    const savedUser = localStorage.getItem('user')
    if (savedUser) {
      try {
        currentUser.value = JSON.parse(savedUser)
      } catch (error) {
        console.error('Failed to parse saved user data:', error)
        localStorage.removeItem('user')
      }
    }
  }

  return {
    currentUser,
    isLoggedIn,
    login,
    logout,
    updateUserInfo,
    updateStatus,
    initUser,
  }
})
